<?php
namespace app\admin\model;
use think\Model;
class  Ouser extends Model
{
    public function import_users(array $users_info,$warehouse_id)
    {
        $ouser = new Ouser;
        $list = array();
        foreach ($users_info as $uk => $uv){
            $sub_list = array();
            $sub_list['user_name'] = $uv[0];
            $sub_list['password'] = md5($uv[1]);
            $sub_list['warehouse_id'] = $warehouse_id;
            $sub_list['created'] = time();
            array_push($list, $sub_list);
        }
        $result = $ouser->saveAll($list);
        if ($result == false){
            return false;
        }
        return true;
    }
    
    public function save_ouser(array $ouserInfo)
    {
        $ouser = new Ouser;
        $list = [
            'user_name' => $ouserInfo['user_name']
        ];
        if (isset($ouserInfo['id'])){
            $list['password'] = md5($ouserInfo['password']);
            $result = $ouser->save($list,['id'=>$ouserInfo['id']]);
        }else {
            $list['warehouse_id'] = $ouserInfo['warehouse_id'];
            $list['created'] = time();
            $result = $ouser->save($list);
            $result = $ouser->id;
        }
        return $result;
    }
    
    public function regulateOuserList(array $ouser_list)
    {
    	$warehouse_model = model('Warehouse');
    	$warehouse_list = $warehouse_model->getAllWarehouse();
    	foreach ($ouser_list as $ok => &$ov){
    		$ov['created'] = date('Y-m-d',$ov['created']);
    		foreach ($warehouse_list as $wk => $wv){
    			if ($wv['id'] == $ov['warehouse_id']){
    				$ov['warehouse'] = $wv['warehouse'];
    			}
    		}
    	}
    	return $ouser_list;
    }
    
    public function tmpToOuser($tmp_ouser_id,$if_agree)
    {
    	$tmp_info = db('ousertmp')->field(['user_name','warehouse_id','password'])->where('id',$tmp_ouser_id)->find();
    	if ($tmp_info == false){
    		return false;
    	}
    	if ($if_agree == '1'){
    		$ouser = new Ouser;
    		$ouser->user_name = $tmp_info['user_name'];
    		$ouser->warehouse_id = $tmp_info['warehouse_id'];
    		$ouser->password = $tmp_info['password'];
    		$ouser->created = time();
    		$ouser->save();
    		$ouser_id = $ouser->id;
    		if ($ouser_id == false){
    			return false;
    		}
    	}
    	$update_agree = db('ousertmp')->where('id',$tmp_ouser_id)->update(['if_agree'=>$if_agree]);
    	if ($update_agree == false){
    		return false;
    	}
    	return isset($ouser_id) ? $ouser_id : true;
    }
    
   
}